import { ref } from 'vue'
import { ElNotification } from 'element-plus'
import { WarningFilled } from '@element-plus/icons-vue'
import { h } from 'vue'

// 存储所有未处理的订单通知
const pendingNotifications = ref([])

// WebSocket连接实例
let socket = null

/**
 * 创建美化的订单通知消息
 * @param {Object} notificationData 订单数据
 * @returns {string} HTML格式的通知消息
 */
function createOrderMessage(notificationData) {
  const orderNumber = notificationData.data.orderNumber;
  const amount = (notificationData.data.amount/100).toFixed(2) || '0.00';
  const customerName = notificationData.data.customerName || '顾客';
  const orderTime = notificationData.data.orderTime || new Date().toLocaleString('zh-CN', { hour12: false });
  
  return `
    <div style="margin-bottom: 8px; font-weight: bold; color: #409EFF; font-size: 15px;">
      🔔 新订单已到达，请及时处理！
    </div>
    <div style="background-color: #F2F6FC; padding: 12px; border-radius: 8px; margin-bottom: 10px; border: 1px solid #DCDFE6;">
      <div style="margin: 6px 0; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #606266; font-weight: 500;">订单号：</span>
        <span style="font-weight: bold; color: #303133;">${orderNumber}</span>
      </div>
      <div style="margin: 6px 0; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #606266; font-weight: 500;">金额：</span>
        <span style="color: #F56C6C; font-weight: bold; font-size: 16px;">¥${amount}</span>
      </div>
      <div style="margin: 6px 0; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #606266; font-weight: 500;">顾客：</span>
        <span style="color: #303133;">${customerName}</span>
      </div>
      <div style="margin: 6px 0; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #606266; font-weight: 500;">时间：</span>
        <span style="color: #303133; font-size: 13px;">${orderTime}</span>
      </div>
    </div>
    <div style="text-align: center; font-size: 13px; color: #909399; padding-top: 5px;">
      点击查看订单详情
    </div>
  `;
}

/**
 * 创建美化的催单通知消息
 * @param {Object} notificationData 催单数据
 * @returns {string} HTML格式的通知消息
 */
function createReminderMessage(notificationData) {
  const orderNumber = notificationData.data.orderNumber;
  const content = notificationData.data.content || '客户催单，请尽快处理！';
  const time = notificationData.data.details?.time || new Date().toLocaleString('zh-CN', { hour12: false });
  
  return `
    <div style="margin-bottom: 10px; color: #E6A23C; font-weight: bold; font-size: 15px;">
      ⚠️ 客户催单提醒，请优先处理！
    </div>
    <div style="background-color: #FDF6EC; padding: 12px; border-radius: 8px; margin-bottom: 10px; border: 1px solid #FAECD8;">
      <div style="margin: 6px 0; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #606266; font-weight: 500;">订单号：</span>
        <span style="font-weight: bold; color: #303133;">${orderNumber}</span>
      </div>
      <div style="margin: 6px 0; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #606266; font-weight: 500;">提醒：</span>
        <span style="color: #E6A23C; font-weight: 500;">${content}</span>
      </div>
      <div style="margin: 6px 0; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #606266; font-weight: 500;">时间：</span>
        <span style="color: #303133; font-size: 13px;">${time}</span>
      </div>
    </div>
    <div style="text-align: center; font-size: 13px; color: #909399; padding-top: 5px;">
      点击查看订单详情
    </div>
  `;
}

// 重连次数与最大重连次数
let reconnectCount = 0
const maxReconnectAttempts = 5
// 重连间隔时间 (ms)
const reconnectInterval = 3000
// 心跳检测定时器
let heartbeatTimer = null
// 重连定时器
let reconnectTimer = null
// 连接状态
const connectionStatus = ref('disconnected') // disconnected, connecting, connected

// 创建自定义事件，用于通知系统中的其他部分
const notificationEvents = new EventTarget();

// 音频元素，用于播放提示音
let notificationAudio = null
let reminderAudio = null

// 初始化音频元素
function initAudio() {
  // 如果已经初始化，则不重复操作
  if (notificationAudio && reminderAudio) return
  
  // 创建新订单提示音
  notificationAudio = new Audio('/sounds/notification.mp3')
  notificationAudio.volume = 0.6
  notificationAudio.preload = 'auto'
  
  // 创建催单提示音
  reminderAudio = new Audio('/sounds/reminder.mp3')
  reminderAudio.volume = 0.7
  reminderAudio.preload = 'auto'
  
  // 预加载音频文件
  try {
    notificationAudio.load()
    reminderAudio.load()
    console.log('音频文件预加载完成')
  } catch (e) {
    console.error('音频预加载失败:', e)
  }
}

/**
 * 初始化WebSocket连接
 * @param {string} sid 会话ID，通常是登录用户的ID
 * @param {Function} onMessageCallback 收到消息的回调函数
 */
export function initWebSocket(sid, onMessageCallback) {
  // 初始化音频
  initAudio()
  
  if (socket && socket.readyState === WebSocket.OPEN) {
    console.log('WebSocket已连接，无需重复初始化')
    return
  }

  // 如果存在旧连接，先关闭
  if (socket) {
    try {
      socket.close()
    } catch (e) {
      console.warn('关闭旧WebSocket连接失败:', e)
    }
    socket = null
  }

  connectionStatus.value = 'connecting'
  try {
    // 生成随机客户端ID，确保每个客户端有唯一标识
    const clientId = sid || Math.random().toString(36).substr(2)
    
    // 首先尝试使用当前页面的主机和协议确定WebSocket URL
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const host = window.location.hostname
    const port = window.location.port
    
    // 尝试多种可能的WebSocket URL格式
    let wsUrls = [];
    
    // 1. 如果没有显式端口（通常是80或443），使用不带端口的URL
    if (!port || port === '80' || port === '443') {
      wsUrls.push(`${protocol}//${host}/ws/${clientId}`);
    } else {
      // 2. 如果有显式端口，包含端口号
      wsUrls.push(`${protocol}//${host}:${port}/ws/${clientId}`);
    }
    
    // 3. 如果是开发环境，添加开发服务器的URL
    if (process.env.NODE_ENV === 'development') {
      wsUrls.push(`ws://localhost:3001/ws/${clientId}`);
    }
    
    // 让我们在控制台记录所有可能尝试的URL
    console.log('将尝试以下WebSocket连接URL:', wsUrls);
    
    // 选择第一个WebSocket URL尝试连接 
    let wsUrl = wsUrls[0];
    
    console.log('尝试连接WebSocket:', wsUrl)
    
    // 创建连接前，先设置连接超时
    const connectionTimeout = setTimeout(() => {
      if (connectionStatus.value === 'connecting') {
        console.warn('WebSocket连接超时，尝试其他连接地址')
        connectionStatus.value = 'disconnected'
        
        // 尝试其他URL
        if (wsUrls.length > 1) {
          let nextUrl = wsUrls[1];
          console.log('尝试备用连接:', nextUrl);
          wsUrls.shift(); // 移除第一个已尝试的URL
          
          // 如果仍然失败，延时尝试下一个URL
          setTimeout(() => {
            if (connectionStatus.value !== 'connected') {
              initWebSocket(sid, onMessageCallback);
            }
          }, 1000);
        } else {
          // 可以选择显示通知，但不要过多打扰用户
          if (reconnectCount >= 2) {
            ElNotification({
              title: '连接提示',
              message: '订单通知服务连接超时，可能影响接收实时订单',
              type: 'warning',
              duration: 3000
            })
          }
        }
      }
    }, 5000)
    
    socket = new WebSocket(wsUrl)

    // 连接建立
    socket.onopen = () => {
      console.log('WebSocket连接已建立 - 成功连接到:', wsUrl)
      connectionStatus.value = 'connected'
      reconnectCount = 0
      clearTimeout(connectionTimeout)
      
      // 开始心跳检测
      startHeartbeat()
      
      // 发送一个测试消息以验证连接
      setTimeout(() => {
        try {
          if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify({
              type: 'connect',
              message: 'Hello Server, WebSocket connection established',
              clientId: clientId,
              timestamp: new Date().getTime()
            }));
            console.log('发送测试消息成功');
          }
        } catch (e) {
          console.error('发送测试消息失败:', e);
        }
      }, 500);
    }

    // 接收消息
    socket.onmessage = (event) => {
      console.log('收到WebSocket消息:', event.data)
      try {
        // 尝试解析JSON消息
        let message = event.data
        
        if (typeof event.data === 'string') {
          try {
            message = JSON.parse(event.data)
          } catch (e) {
            // 如果解析失败，则处理为纯文本消息
            console.log('收到的不是JSON格式消息，作为纯文本处理')
            message = {
              type: 'text',
              content: event.data
            }
          }
        }
        
        // 处理不同类型的消息
        if (message.type === 'heartbeat') {
          // 心跳响应，无需处理
          return
        } else if (message.type === 1 || message.type === 'newOrder') {
          // 新订单通知 - 播放提示音
          playNotificationSound()
          
          // 添加到待处理通知列表 - 仅保存基本信息
          const notificationData = {
            id: message.orderId || message.id || Date.now().toString(),
            timestamp: Date.now(),
            data: {
              id: message.orderId || message.id,
              orderNumber: message.orderNumber || message.content || '未知订单',
              orderTime: message.orderTime || new Date().toLocaleString('zh-CN', { hour12: false }),
            },
            read: false,
            type: 1, // 新订单
            needsDetails: true // 标记该通知需要手动获取详情
          }
          
          console.log('处理后的通知数据:', notificationData);
          
          // 添加到通知列表，确保订单号唯一性
          const existingNotificationIndex = pendingNotifications.value.findIndex(
            item => (item.data.orderNumber === notificationData.data.orderNumber)
          );
          
          if (existingNotificationIndex >= 0) {
            console.log(`已存在相同订单号的通知，更新: ${notificationData.data.orderNumber}`);
            pendingNotifications.value[existingNotificationIndex] = notificationData;
          } else {
            console.log(`添加新订单通知: ${notificationData.data.orderNumber}`);
            pendingNotifications.value.push(notificationData);
          }
          
          // 触发全局事件
          window.dispatchEvent(new CustomEvent('new-order-received', { detail: notificationData }));
          
          // 发送自定义事件，通知系统其他部分
          const event = new CustomEvent('newOrderNotification', { 
            detail: notificationData 
          });
          notificationEvents.dispatchEvent(event);
          
        } else if (message.type === 2 || message.type === 'reminder') {
          // 催单提醒 - 播放提示音
          playReminderSound()
          
          // 添加到待处理通知列表
          const notificationData = {
            id: message.orderId || message.id || Date.now().toString(),
            timestamp: Date.now(),
            data: {
              id: message.orderId || message.id,
              orderNumber: message.orderNumber || message.orderId || '未知订单',
              content: message.content || '客户催单',
              details: message.details || {}
            },
            read: false,
            type: 2 // 催单
          }
          
          // 添加到通知列表，检查是否已存在相同ID的催单
          const existingNotificationIndex = pendingNotifications.value.findIndex(
            item => (item.data.orderNumber === notificationData.data.orderNumber && item.type === 2)
          );
          
          if (existingNotificationIndex >= 0) {
            console.log(`已存在相同订单号的催单通知，更新: ${notificationData.data.orderNumber}`);
            pendingNotifications.value[existingNotificationIndex] = notificationData;
          } else {
            console.log(`添加新催单通知: ${notificationData.data.orderNumber}`);
            pendingNotifications.value.push(notificationData);
          }
          
          // 触发全局事件
          window.dispatchEvent(new CustomEvent('order-reminder-received', { detail: notificationData }));
          
          // 发送自定义事件，通知系统其他部分
          const event = new CustomEvent('newReminderNotification', { 
            detail: notificationData 
          });
          notificationEvents.dispatchEvent(event);
          
        } else if (message.type === 'text') {
          // 纯文本消息，显示一个通知
          ElNotification({
            title: '系统消息',
            message: message.content,
            type: 'info',
            duration: 5000
          })
        }

        // 调用自定义消息处理回调
        if (onMessageCallback) {
          onMessageCallback(message)
        }
      } catch (error) {
        console.error('处理WebSocket消息失败:', error, '原始消息:', event.data)
        
        // 对于无法解析的消息，尝试直接显示
        if (typeof event.data === 'string') {
          ElNotification({
            title: '收到消息',
            message: event.data,
            type: 'info',
            duration: 5000
          })
        }
      }
    }

    // 连接关闭
    socket.onclose = (event) => {
      console.log('WebSocket连接已关闭', event)
      connectionStatus.value = 'disconnected'
      clearTimeout(connectionTimeout)
      stopHeartbeat()
      
      // 尝试重连
      if (reconnectCount < maxReconnectAttempts) {
        console.log(`${reconnectInterval / 1000}秒后尝试重连...`)
        reconnectTimer = setTimeout(() => {
          reconnectCount++
          initWebSocket(sid, onMessageCallback)
        }, reconnectInterval)
      } else {
        console.error('WebSocket重连次数已达上限，不再重连')
        // 只在最后一次尝试后显示通知，避免过多打扰用户
        ElNotification({
          title: '连接断开',
          message: '订单实时通知服务连接失败，可能无法接收订单通知',
          type: 'error',
          duration: 10000
        })
      }
    }

    // 错误处理
    socket.onerror = (error) => {
      console.error('WebSocket发生错误:', error)
      console.error('错误详情:', {
        url: wsUrl,
        readyState: socket ? socket.readyState : 'no socket',
        error: error
      })
      connectionStatus.value = 'disconnected'
      clearTimeout(connectionTimeout)
      
      // 不在这里显示错误通知，让onclose处理重连
    }
  } catch (error) {
    console.error('初始化WebSocket失败:', error)
    connectionStatus.value = 'disconnected'
    
    // 严重错误时通知用户
    if (reconnectCount >= maxReconnectAttempts) {
      ElNotification({
        title: '连接错误',
        message: '订单通知服务无法启动，可能影响接收实时订单',
        type: 'error',
        duration: 5000
      })
    }
  }
}

/**
 * 关闭WebSocket连接
 */
export function closeWebSocket() {
  stopHeartbeat()
  
  if (reconnectTimer) {
    clearTimeout(reconnectTimer)
    reconnectTimer = null
  }
  
  if (socket) {
    try {
      socket.close()
      socket = null
      connectionStatus.value = 'disconnected'
      console.log('WebSocket连接已关闭')
    } catch (e) {
      console.error('关闭WebSocket连接失败:', e)
    }
  }
}

/**
 * 开始心跳检测
 */
function startHeartbeat() {
  // 清除可能存在的旧定时器
  stopHeartbeat()
  
  // 每30秒发送一次心跳
  heartbeatTimer = setInterval(() => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      // 发送心跳消息
      socket.send(JSON.stringify({ type: 'heartbeat' }))
    }
  }, 30000)
}

/**
 * 停止心跳检测
 */
function stopHeartbeat() {
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer)
    heartbeatTimer = null
  }
}

/**
 * 播放新订单提示音
 */
function playNotificationSound() {
  try {
    if (!notificationAudio) {
      initAudio()
    }
    
    notificationAudio.currentTime = 0
    notificationAudio.play().catch(error => {
      console.error('播放新订单提示音失败:', error)
    })
  } catch (error) {
    console.error('播放新订单提示音出错:', error)
  }
}

/**
 * 播放催单提示音
 */
function playReminderSound() {
  try {
    if (!reminderAudio) {
      initAudio()
    }
    
    reminderAudio.currentTime = 0
    reminderAudio.play().catch(error => {
      console.error('播放催单提示音失败:', error)
    })
  } catch (error) {
    console.error('播放催单提示音出错:', error)
  }
}

/**
 * 显示订单通知
 * @param {Object} notificationData 通知数据
 * @param {string} content 可选的自定义内容
 */
export function showOrderNotification(notificationData, content) {
  // 播放通知音效
  playNotificationSound();
  
  // 发送自定义事件，通知系统其他部分
  const event = new CustomEvent('newOrderNotification', { 
    detail: notificationData 
  });
  notificationEvents.dispatchEvent(event);
}

/**
 * 显示催单通知
 * @param {Object} notificationData 通知数据
 * @param {string} content 可选的自定义内容
 */
export function showReminderNotification(notificationData, content) {
  // 播放催单音效
  playReminderSound();
  
  // 发送自定义事件，通知系统其他部分
  const event = new CustomEvent('newReminderNotification', { 
    detail: notificationData 
  });
  notificationEvents.dispatchEvent(event);
}

// 获取未读通知数量
export function getUnreadNotificationCount() {
  if (!pendingNotifications.value || pendingNotifications.value.length === 0) {
    return 0
  }
  return pendingNotifications.value.filter(item => !item.read).length
}

// 获取所有通知
export function getPendingNotifications() {
  return pendingNotifications.value
}

// 标记通知为已读
export function markNotificationAsRead(id) {
  const notification = pendingNotifications.value.find(item => item.id === id)
  if (notification) {
    notification.read = true
  }
  return pendingNotifications.value
}

// 标记所有通知为已读
export function markAllNotificationsAsRead() {
  pendingNotifications.value.forEach(item => {
    item.read = true
  })
  return pendingNotifications.value
}

// 删除指定通知
export function removeNotification(id) {
  const index = pendingNotifications.value.findIndex(item => item.id === id)
  if (index > -1) {
    pendingNotifications.value.splice(index, 1)
  }
  return pendingNotifications.value
}

// 清空所有通知
export function clearAllNotifications() {
  pendingNotifications.value = []
  return pendingNotifications.value
}

/**
 * 发送消息到WebSocket服务器（用于测试连接）
 */
export function sendMessage(message) {
  if (!socket || socket.readyState !== WebSocket.OPEN) {
    console.error('WebSocket未连接，无法发送消息')
    ElNotification({
      title: '连接错误',
      message: 'WebSocket未连接，请刷新页面重试',
      type: 'error',
      duration: 3000
    })
    return false
  }
  
  try {
    socket.send(typeof message === 'string' ? message : JSON.stringify(message))
    return true
  } catch (error) {
    console.error('发送消息失败:', error)
    return false
  }
}

/**
 * 测试WebSocket连接
 * @returns {Promise<Object>} 测试结果
 */
export function testConnection() {
  return new Promise((resolve) => {
    // 如果已经连接，直接返回成功
    if (socket && socket.readyState === WebSocket.OPEN) {
      resolve({
        connected: true,
        status: 'connected',
        message: 'WebSocket已连接',
        readyState: socket.readyState
      });
      return;
    }
    
    // 如果正在连接中，返回等待状态
    if (socket && socket.readyState === WebSocket.CONNECTING) {
      resolve({
        connected: false,
        status: 'connecting',
        message: 'WebSocket正在连接中',
        readyState: socket.readyState
      });
      return;
    }
    
    console.log('开始测试WebSocket连接...');
    
    // 设置测试超时
    const timeout = setTimeout(() => {
      resolve({
        connected: false,
        status: 'timeout',
        message: 'WebSocket连接测试超时',
        readyState: socket ? socket.readyState : 'not_initialized'
      });
    }, 5000);
    
    // 尝试创建临时WebSocket连接进行测试
    const testUserID = 'test-' + Math.random().toString(36).substr(2, 9);
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.hostname;
    const port = window.location.port;
    
    // 尝试多个可能的WebSocket URL
    const wsUrls = [];
    
    // 1. 如果没有显式端口（通常是80或443），使用不带端口的URL
    if (!port || port === '80' || port === '443') {
      wsUrls.push(`${protocol}//${host}/ws/${testUserID}`);
    } else {
      // 2. 如果有显式端口，包含端口号
      wsUrls.push(`${protocol}//${host}:${port}/ws/${testUserID}`);
    }
    
    // 3. 如果是开发环境，添加开发服务器的URL
    if (process.env.NODE_ENV === 'development') {
      wsUrls.push(`ws://localhost:3001/ws/${testUserID}`);
    }
    
    let wsUrl = wsUrls[0];
    
    console.log('测试连接到:', wsUrl);
    
    try {
      const testSocket = new WebSocket(wsUrl);
      
      // 设置事件监听器
      testSocket.onopen = () => {
        clearTimeout(timeout);
        console.log('测试WebSocket连接成功');
        
        // 发送测试消息
        try {
          testSocket.send(JSON.stringify({
            type: 'test',
            message: 'Test connection message',
            clientId: testUserID,
            timestamp: new Date().getTime()
          }));
        } catch (e) {
          console.warn('发送测试消息失败:', e);
        }
        
        // 清理连接
        setTimeout(() => {
          try {
            testSocket.close();
          } catch (e) {
            console.warn('关闭测试连接失败:', e);
          }
        }, 500);
        
        resolve({
          connected: true,
          status: 'connected',
          message: 'WebSocket连接测试成功',
          url: wsUrl
        });
      };
      
      testSocket.onerror = (event) => {
        console.error('测试WebSocket连接失败:', event);
        
        // 如果有更多URL可以尝试
        if (wsUrls.length > 1) {
          wsUrls.shift(); // 移除第一个已尝试的URL
          const nextUrl = wsUrls[0];
          console.log('尝试下一个WebSocket URL:', nextUrl);
          
          // 等待一段时间再尝试下一个URL
          setTimeout(() => {
            try {
              const nextSocket = new WebSocket(nextUrl);
              
              nextSocket.onopen = () => {
                clearTimeout(timeout);
                console.log('备用URL连接成功:', nextUrl);
                
                // 清理连接
                setTimeout(() => {
                  try {
                    nextSocket.close();
                  } catch (e) {
                    console.warn('关闭备用连接失败:', e);
                  }
                }, 500);
                
                resolve({
                  connected: true,
                  status: 'connected',
                  message: '备用WebSocket连接成功',
                  url: nextUrl
                });
              };
              
              nextSocket.onerror = () => {
                // 所有URL都失败了
                clearTimeout(timeout);
                resolve({
                  connected: false,
                  status: 'error',
                  message: '所有WebSocket连接尝试均失败',
                  urls: wsUrls
                });
              };
              
            } catch (nextError) {
              clearTimeout(timeout);
              console.error('尝试备用URL失败:', nextError);
              resolve({
                connected: false,
                status: 'error',
                message: '无法创建WebSocket连接: ' + nextError.message,
                error: String(nextError)
              });
            }
          }, 1000);
          
        } else {
          // 没有更多URL可尝试
          clearTimeout(timeout);
          resolve({
            connected: false,
            status: 'error',
            message: 'WebSocket连接失败',
            url: wsUrl,
            error: event ? String(event) : 'Unknown error'
          });
        }
      };
      
      testSocket.onclose = () => {
        // 只有在连接建立后关闭时才处理
        // 连接失败会触发error事件，已经在onerror中处理
      };
      
    } catch (error) {
      clearTimeout(timeout);
      console.error('创建WebSocket测试连接失败:', error);
      resolve({
        connected: false,
        status: 'error',
        message: '无法创建WebSocket连接: ' + error.message,
        error: String(error)
      });
    }
  });
}

/**
 * 获取订单详情数据
 * @param {Object} notificationData 通知数据
 */
async function fetchOrderDetail(notificationData) {
  if (!notificationData || !notificationData.data || !notificationData.data.id) {
    console.log('通知数据不完整，无法获取订单详情');
    return;
  }
  
  try {
    // 构建请求URL - 使用与应用相同的基础URL
    const baseUrl = window.location.origin;
    const apiUrl = `${baseUrl}/api/admin/order/details/${notificationData.data.id}`;
    
    console.log('获取订单详情:', apiUrl);
    
    // 获取token
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (!token) {
      console.warn('未找到认证token，无法获取订单详情');
      return;
    }
    
    // 发送请求
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'token': token
      }
    });
    
    if (!response.ok) {
      throw new Error(`订单详情请求失败: ${response.status} ${response.statusText}`);
    }
    
    const result = await response.json();
    
    if (result.code === 1 && result.data) {
      console.log('获取到完整订单数据:', result.data);
      
      // 更新通知中的数据
      const updatedIndex = pendingNotifications.value.findIndex(
        item => item.data.id === notificationData.data.id || 
               item.data.orderNumber === notificationData.data.orderNumber
      );
      
      if (updatedIndex >= 0) {
        // 合并原通知和新获取的详情数据
        const updatedNotification = {
          ...pendingNotifications.value[updatedIndex],
          data: {
            ...pendingNotifications.value[updatedIndex].data,
            id: result.data.id,
            orderNumber: result.data.number,
            orderTime: result.data.orderTime,
            amount: formatAmount(result.data.amount),
            customerName: result.data.consignee || '顾客',
            address: result.data.address || '',
            phone: result.data.phone || '',
            status: result.data.status,
            payStatus: result.data.payStatus,
            payMethod: result.data.payMethod,
            remark: result.data.remark,
            orderDetailList: result.data.orderDetailList || []
          },
          completeData: result.data, // 存储完整的订单数据
          complete: true // 标记为已获取完整数据
        };
        
        // 更新通知列表
        pendingNotifications.value[updatedIndex] = updatedNotification;
        
        console.log('订单通知数据已更新:', updatedNotification);
        
        // 发送更新事件
        window.dispatchEvent(new CustomEvent('notification-data-updated', { 
          detail: updatedNotification 
        }));
      }
    } else {
      console.error('获取订单详情失败:', result.msg || '未知错误');
    }
  } catch (error) {
    console.error('获取订单详情出错:', error);
  }
}

/**
 * 格式化金额显示
 * @param {number|string} amount 金额数值
 * @returns {string} 格式化后的金额
 */
function formatAmount(amount) {
  if (typeof amount === 'undefined' || amount === null) {
    return '0.00';
  }
  
  // 如果是数字，则格式化为两位小数
  if (typeof amount === 'number') {
    return amount.toFixed(2);
  }
  
  // 如果是字符串，尝试转换为数字再格式化
  if (typeof amount === 'string') {
    const numAmount = parseFloat(amount);
    if (!isNaN(numAmount)) {
      return numAmount.toFixed(2);
    }
  }
  
  return '0.00';
}

export {
  connectionStatus,
  notificationEvents
}